package org.glut.wechat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.glut.wechat.service.IVideoService;
import org.glut.wechat.domain.Video;
import org.glut.wechat.mapper.VideoMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.glut.wechat.util.AliOssUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import org.apache.tika.Tika;

/**
 * 视频表 服务实现类
 *
 * @author fy
 * @since 2025-08-22 21:52
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements IVideoService {

    private static final Logger log = LoggerFactory.getLogger(VideoServiceImpl.class);

    @Autowired
    private AliOssUtils aliOssUtils;

    @Override
    public List<Video> getVideoList() {
        List<Video> videos = list();
        if (videos == null) {
            return new ArrayList<>();
        }
        videos.forEach(video -> {
            if (video != null && video.getVideoFileName() != null && !video.getVideoFileName().isEmpty()) {
                // 使用直接访问URL而非带签名的URL
                String videoUrl = aliOssUtils.getDirectVideoUrl(video.getVideoFileName());
                video.setVideoUrl(videoUrl);
            }
        });
        return videos;
    }

    @Override
    public String uploadVideo(MultipartFile video, String title, String description) {
        try {
            String originalFilename = video.getOriginalFilename();
            if (originalFilename == null) {
                throw new RuntimeException("无效的视频文件名");
            }
            // 提取文件名和扩展名
            String fileNameWithoutPath = originalFilename.replaceAll(".*[/\\\\]", "");
            int dotIndex = fileNameWithoutPath.lastIndexOf(".");
            if (dotIndex == -1) {
                throw new RuntimeException("视频文件缺少扩展名");
            }
            String fileExtension = fileNameWithoutPath.substring(dotIndex + 1).toLowerCase();

            // 使用Tika检测文件类型
            try (InputStream inputStream = video.getInputStream()) {
                Tika tika = new Tika();
                String detectedType = tika.detect(inputStream);
                // 验证文件类型和扩展名
                boolean isValidType = detectedType.startsWith("video/") && (
                        "mp4".equals(fileExtension) || "webm".equals(fileExtension) || "ogg".equals(fileExtension));
                if (!isValidType) {
                    throw new RuntimeException("不支持的视频文件类型");
                }
            }

            // 生成唯一文件名
            String fileName = UUID.randomUUID().toString() + fileNameWithoutPath.substring(dotIndex);

            // 1. 上传文件到OSS（补充缺失的上传逻辑）
            aliOssUtils.uploadVideoFile(fileName, video);

            // 2. 创建Video对象并保存到数据库
            Video videoEntity = new Video();
            videoEntity.setVideoFileName(fileName); // 存储OSS中的文件名
            videoEntity.setTitle(title);           // 设置视频标题
            videoEntity.setDescription(description); // 设置视频描述
            videoEntity.setLikes(0);
            videoEntity.setComments(0);
            videoEntity.setVideoUserid(null);
            videoEntity.setVideoUsername(null);
            this.save(videoEntity);

            return fileName;
        } catch (Exception e) {
            log.error("视频上传失败", e);
            throw new RuntimeException("视频上传失败：" + e.getMessage(), e);
        }
    }
    @Override
    public Video getRandomVideo(List<Integer> excludeIds) {
        QueryWrapper<Video> queryWrapper = new QueryWrapper<>();
        if (excludeIds != null && !excludeIds.isEmpty()) {
            queryWrapper.notIn("video_id", excludeIds);
        }

        // 获取符合条件的总记录数
        long count = count(queryWrapper);
        if (count == 0) {
            return null;
        }

        // 生成随机偏移量
        int randomOffset = new Random().nextInt((int) count);

        // 随机获取一条记录
        List<Video> videos = baseMapper.selectList(
                queryWrapper.last("LIMIT 1 OFFSET " + randomOffset)
        );

        if (videos != null && !videos.isEmpty()) {
            Video video = videos.get(0);
            if (video.getVideoFileName() != null && !video.getVideoFileName().isEmpty()) {
                video.setVideoUrl(aliOssUtils.getDirectVideoUrl(video.getVideoFileName()));
            }
            return video;
        }
        return null;
    }
}